package qwq.zyu.spigotPluginTianguo.Command;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import qwq.zyu.spigotPluginTianguo.SpigotPluginTianguo;
import qwq.zyu.spigotPluginTianguo.VideoPlayer;

public class StopTianguoCommand implements CommandExecutor {

    private final SpigotPluginTianguo plugin;
    private final VideoPlayer videoPlayer;

    public StopTianguoCommand(SpigotPluginTianguo plugin, VideoPlayer videoPlayer) {
        this.plugin = plugin;
        this.videoPlayer = videoPlayer;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        String senderType;
        if (sender instanceof Player) {
            senderType = "Player";
        } else if (sender.getName().equals("CONSOLE")) {
            senderType = "Console";
        } else {
            senderType = "CommandBlock";
        }
        String senderName = sender.getName();

        plugin.getLogger().info("[stopTianguo] Command executed by: " + senderType + " (" + senderName + ")");

        if (!plugin.isCommandStopEnabled()) {
            sender.sendMessage(ChatColor.RED + "Command-triggered stop is disabled!");
            plugin.getLogger().warning("[stopTianguo] Command stop is disabled.");
            return true;
        }

        if (!videoPlayer.isPlaying()) {
            sender.sendMessage(ChatColor.YELLOW + "No Tianguo video is currently playing!");
            return true;
        }

        videoPlayer.stop();
        plugin.getLogger().info("[stopTianguo] Playback stopped successfully.");

        if (plugin.isAudioEnabled()) {
            plugin.getServer().dispatchCommand(
                plugin.getServer().getConsoleSender(),
                "stopsound @a record niacl:music_disc.tententengoku_jigokukoku"
            );
        }

        plugin.resetCooldown();

        String executorDisplayName = sender instanceof Player ? sender.getName() : senderType;
        plugin.getServer().broadcastMessage(ChatColor.RED + "[Tianguo] " + executorDisplayName + " stopped the show!");
        plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Tianguo] Cooldown has been reset.");

        return true;
    }
}
